#include "kernel_operator.h"
constexpr int32_t BUFFER_NUM = 2; // tensor num for each queue

template<typename TYPE_X, typename TYPE_Z, bool IsExistBigCore> 
class KernelMish {
public:
    __aicore__ inline KernelMish() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, uint32_t smallCoreDataNum,
                                uint32_t bigCoreDataNum, uint32_t bigCoreLoopNum, 
                                uint32_t smallCoreLoopNum, uint32_t ubPartDataNum, 
                                uint32_t smallCoreTailDataNum, uint32_t bigCoreTailDataNum, 
                                uint32_t tailBlockNum) 
    {
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint32_t coreNum = AscendC::GetBlockIdx();
        uint32_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->ubPartDataNum = ubPartDataNum;
        
        if constexpr (IsExistBigCore) 
        {
          if (coreNum < tailBlockNum) 
          { 
            this->coreDataNum = bigCoreDataNum;
            this->tileNum = bigCoreLoopNum;
            this->tailDataNum = bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = smallCoreDataNum;
            this->tileNum = smallCoreLoopNum;
            this->tailDataNum = smallCoreTailDataNum;
            globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = smallCoreLoopNum;
          this->tailDataNum = smallCoreTailDataNum;
          globalBufferIndex = smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ TYPE_Z*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Z));
        pipe.InitBuffer(tmpBuf0, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf1, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf2, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf3, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf4, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf5, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf6, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(tmpBuf7, this->ubPartDataNum * sizeof(TYPE_X));
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;

        for (int32_t i = 0; i < (loopCount-1); i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;

        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
        AscendC::DataCopy(xLocal, xGm[progress * this->ubPartDataNum], this->processDataNum);
        inQueueX.EnQue(xLocal);
    }

    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
        AscendC::LocalTensor<TYPE_X> zLocal = outQueueZ.AllocTensor<TYPE_X>();
        AscendC::LocalTensor<TYPE_X> tmp0 = tmpBuf0.Get<TYPE_X>();
        AscendC::LocalTensor<TYPE_X> tmp1 = tmpBuf1.Get<TYPE_X>();
        AscendC::LocalTensor<TYPE_X> tmp2 = tmpBuf2.Get<TYPE_X>();
        AscendC::LocalTensor<TYPE_X> tmp3 = tmpBuf3.Get<TYPE_X>(); 
        AscendC::LocalTensor<TYPE_X> tmp4 = tmpBuf4.Get<TYPE_X>(); 
        AscendC::LocalTensor<TYPE_X> tmp5 = tmpBuf5.Get<TYPE_X>(); 
        AscendC::LocalTensor<TYPE_X> tmp6 = tmpBuf6.Get<TYPE_X>();
        AscendC::LocalTensor<TYPE_X> tmp7 = tmpBuf7.Get<TYPE_X>();

        // z = x · tanh( ln( 1 + e ^ {x} ) )
        // ln( 1 + e ^ {x} )  ->  ln(e^0 + e^x) = max(0,x) + ln(1 + e^(-|x|))
        //  tmp0 = max(0, x)
        AscendC::Maxs(tmp0, xLocal, (TYPE_X)0.0, this->processDataNum);

        // tmp1 = | x |
        AscendC::Abs(tmp1, xLocal, this->processDataNum);
        // tmp2 = - | x |
        AscendC::Muls(tmp2, tmp1, (TYPE_X)(-1.0), this->processDataNum);
        // tmp3 = e ^ ( - | x | )
        AscendC::Exp(tmp3, tmp2, this->processDataNum);
        // tmp4 = 1 +  e ^ ( - | x | )
        AscendC::Adds(tmp4, tmp3, (TYPE_X)1.0, this->processDataNum);
        // tmp5 = ln(1 + e^(-|x|))
        AscendC::Ln(tmp5, tmp4, this->processDataNum);

        // tmp6 = max(0,x) + ln(1 + e^(-|-x|))
        AscendC::Add(tmp6, tmp5, tmp0, this->processDataNum);

        // tmp7 = tanh( tmp6 )
        AscendC::Tanh(tmp7, tmp6, this->processDataNum);

        // z = x · tanh( ln( 1 + e ^ {x} ) )
        AscendC::Mul(zLocal, tmp7, xLocal, this->processDataNum);

        outQueueZ.EnQue<TYPE_X>(zLocal);
        inQueueX.FreeTensor(xLocal);

    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.DeQue<TYPE_Z>();  
        AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf0;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf1;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf2;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf3;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf4;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf5;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf6;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf7;


    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Z> zGm;
    uint32_t coreDataNum;
    uint32_t tileNum;
    uint32_t ubPartDataNum;
    uint32_t tailDataNum;
    uint32_t processDataNum;
};

extern "C" __global__ __aicore__ void mish_custom(GM_ADDR x, GM_ADDR z, GM_ADDR workspace, GM_ADDR tiling)
{
    GET_TILING_DATA(tiling_data, tiling);              
    if(TILING_KEY_IS(1))
    {
      KernelMish<DTYPE_X, DTYPE_Z, true> op;
      op.Init(x, z, tiling_data.smallCoreDataNum,
                tiling_data.bigCoreDataNum, tiling_data.bigCoreLoopNum,
                tiling_data.smallCoreLoopNum, tiling_data.ubPartDataNum,
                tiling_data.smallCoreTailDataNum, tiling_data.bigCoreTailDataNum,
                tiling_data.tailBlockNum);
      op.Process();       
    }
    else if(TILING_KEY_IS(0))
    {
      KernelMish<DTYPE_X, DTYPE_Z, false> op;
      op.Init(x, z, tiling_data.smallCoreDataNum,
                tiling_data.bigCoreDataNum, tiling_data.bigCoreLoopNum,
                tiling_data.smallCoreLoopNum, tiling_data.ubPartDataNum,
                tiling_data.smallCoreTailDataNum, tiling_data.bigCoreTailDataNum,
                tiling_data.tailBlockNum);
      op.Process();   
    }
}